#!/usr/bin/env python3

import os
import subprocess
import sys

from os.path import abspath, dirname, isfile, join

redex_path = abspath(join(dirname(abspath(__file__)), '../'))
sys.path.append(redex_path)

import redex
import pyredex.unpacker as unpacker
import pyredex.utils as utils


def redexdump_binary():
    try:
        binary = subprocess.check_output(
            'which redexdump 2>/dev/null',
            shell=True)
        return binary.rstrip()
    except:
        pass
    binary = join(redex_path, 'redexdump')
    if isfile(binary):
        return binary
    binary = join(redex_path, '../../buck-out/gen/native/redex/redexdump')
    if isfile(binary):
        return binary
    raise Exception('Cannot locate redexdump')


if __name__ == '__main__':
    args = sys.argv[1:]
    apk = None
    options = []
    for arg in args:
        if not arg.startswith('--'):
            apk = arg
        else:
            options.append(arg)
    if apk is None:
        sys.exit('No apk given')

    apk_dir = redex.make_temp_dir('.apk_dir')
    dex_dir = redex.make_temp_dir('.dex_dir')

    utils.unzip_apk(apk, apk_dir)
    dex_mode = unpacker.detect_secondary_dex_mode(apk_dir)
    dex_mode.unpackage(apk_dir, dex_dir)
    dexen = redex.dex_glob(dex_dir)

    subprocess.call([redexdump_binary()] + options + dexen)
